package com.sta.staff.security;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.sta.staff.mapper.UsersMapper;
import com.sta.staff.pojo.Users;
import com.sta.staff.service.UsersService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.context.SecurityContext;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpSession;
import java.util.ArrayList;
import java.util.List;

//自定义认证授权逻辑
@Service
public class MyUserDetailService implements UserDetailsService {
    @Autowired
    private UsersMapper usersMapper;
    @Autowired
    private UsersService usersService;
    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        //1.认证
        Users users = usersService.findByUsersName(username);
        if (users==null){
            throw new UsernameNotFoundException("用户不存在");
        }


        //2.授权
        Boolean status= usersService.findByUsersName1(username);
        List<GrantedAuthority> grantedAuthorities =new ArrayList();
        if (status){
            grantedAuthorities.add(new SimpleGrantedAuthority("/boss"));
        }else {
            grantedAuthorities.add(new SimpleGrantedAuthority("/worker"));
        }

        
        //封装为UserDetail对象
        UserDetails userDetails = User.withUsername(users.getUsername())
                .password(users.getPassword())
                .authorities(grantedAuthorities)
                .build();
        return userDetails;
    }
}
